<?php 

class myDoctrineIndexedRecord extends sfDoctrineRecord
{
	/**
	 * Override save method
	 * @param Doctrine_Connection $conn
	 */
	public function save(Doctrine_Connection $conn = null)
	{
		// Check for doctrine connections object
		if(!is_object($conn))
			// Set new connection object
			$conn = $this->getTable()->getConnection();

		// Begin transaction
		$conn->beginTransaction();
		
		try
		{
			$ret = parent::save($conn);
			$this->updateLuceneIndex();
			$conn->commit();
			return $ret;
		}catch(Exception $e)
		{
			$conn->rollBack();
			throw $e;
		}
	}	
	/**
	 * Override delete method
	 * @param Doctrine_Connection $conn
	 */
	public function delete(Doctrine_Connection $conn = null)
	{
		// Get lucene index
		$index = $this->getTable()->getLuceneIndex();
		
		// Delete lucene index
		foreach($index->find('pk:' . $this->getId()) as $hit)
			$index->delete($hit->id);
		
		return parent::delete($conn);
	}
	/**
	 * Method to update lucene index
	 */
	public function updateLuceneIndex()
	{
		// Get fields for indexing
		$indexed_fields = sfConfig::get('app_indexing_' . $this->getTable()->getTableName());
		// Check for fields list
		if(!is_array($indexed_fields))
			return false;
		// Check for not empty list
		if(!count($indexed_fields))
			return false;		
		
		// Get index
		$index = $this->getTable()->getLuceneIndex();
		
		// Clear existed index
		foreach($index->find('pk:' . $this->getId()) as $hit)
			$index->delete($hit->id);
		
		// Make new lucene document
		$doc = new Zend_Search_Lucene_Document();
		
		// Store key
		$doc->addField(Zend_Search_Lucene_Field::Keyword('pk', $this->getId()));
		
		// Get indexing encoding
		$encoding = sfConfig::get('app_indexing_encoding');
		
		// Index all needed fields
		foreach($indexed_fields as $field)
			// Make index for needed fields
			$doc->addField(Zend_Search_Lucene_Field::UnStored($field, $this->$field, $encoding));							
			
		// Add document to indexing
		$index->addDocument($doc);
		$index->commit();
	}		
}
